package com.freestyle.nettychat.chat.attachment;

import com.freestyle.netty.easynetty.codes.CustomFrameDecoder;
import com.freestyle.netty.easynetty.common.Utils;
import com.freestyle.nettychat.chat.dto.AttachmentMessage;
import com.freestyle.nettychat.chat.dto.ChatMessageProperties;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.ReferenceCountUtil;
/**
 * Created by rocklee on 2022/2/22 10:06
 */
public class AttachmentDecoder extends CustomFrameDecoder<AttachmentMessage> {
  public AttachmentDecoder(byte[] header) {
    super(header, bytes -> {
      ByteBuf byteBuf= Unpooled.copiedBuffer(bytes);
      try{
        int headerLen=byteBuf.readInt();
        byte[] headerBytes=new byte[headerLen];
        byteBuf.readBytes(headerBytes);
        AttachmentMessage attachmentMessage=new AttachmentMessage();
        attachmentMessage.setProperties(Utils.fromJsonBytes(headerBytes, ChatMessageProperties.class));
        attachmentMessage.setData(ByteBufUtil.getBytes(byteBuf));
        return attachmentMessage;
      }
      finally {
        ReferenceCountUtil.release(byteBuf);
      }
    });
  }
}
